<template>
    <el-dialog
            :title="title"
            :visible.sync="show"
            width="43%"
            :close-on-click-modal="false"
            :before-close="closeDialog"
            @open="openAction"
    >
        <el-transfer
                v-model="selectedRole"
                filterable
                :data="roleData"
                :titles="['未选择角色', '已选择角色']"
                filter-placeholder="请输入角色名称"
                :button-texts="['移除', '增加']"
        />
        <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">关闭</el-button>
        <el-button type="primary" @click="saveRoleRelationship">保存已选角色</el-button>
      </span>
    </el-dialog>
</template>

<script>
    import {listAllRole} from "@/api/role";
    import {updateRoleForUser} from "@/api/userRole";

    export default {
        name: "UserRole",
        data(){
            return {
                roleData:[],
                selectedRole:[]
            }
        },
        props:{
            title:{type:String,default:"关联角色修改"},
            show:{type: Boolean},
            roleInfo:{type:Array},
            userInfo:{type:Object},
        },
        methods:{
            closeDialog(){
                let data = {id:this.userInfo.userId,account:this.userInfo.account}
                this.$emit("update:show",false);
                this.$emit("refreshRole",data)
            },
            //打开窗口的初始化动作
            openAction(){
                this.$nextTick(()=>{
                    listAllRole()
                        .then(res =>{
                            this.roleData = res.data.map(r =>{
                                return {key:r.id,label:r.roleName,disabled:!r.status}
                            })
                            this.selectedRole = this.roleInfo.map(r =>{
                                return r.id
                            })
                        }).catch(err => {
                            this.$message.error(err.message)
                    })
                })
            },
            saveRoleRelationship(){
                let data = {userId:this.userInfo.userId,roleIds:this.selectedRole,account:this.userInfo.account}
                updateRoleForUser(data)
                    .then(res =>{
                        this.$message.success("保存成功！")
                        this.closeDialog()
                    }).catch(err =>{
                        this.$message.error(err.message)
                })
            }
        }
    }
</script>

<style scoped>

</style>